/**
 * Created by huotaol on 2017/5/9.
 */
import React, {Component} from "react";
import {Alert, ScrollView, Text, TextInput, TouchableHighlight, TouchableOpacity, View} from "react-native";
import CustomStyle from "../../../common/style/CustomStyle";
import {connect} from "react-redux";
import Util from "../../main/Util";
import {Actions} from "react-native-router-flux";
import Toast from "react-native-root-toast";
import * as MineAction from "../../redux/action/Mine";
import {styles} from "./LoginUI";
import ModuleCommonHeader from "../../main/module/ModuleCommonHeader";

class Register extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            phone: '',
            password: '',
            passwordConfirm: '',
            verifyCode: '',
            requestingVerifyCode: false,
            verifyText: '获取验证码',
        };
        this._register = this._register.bind(this);
        this._register = this._register.bind(this);
    }

    render() {
        return (
            <ScrollView >
                <ModuleCommonHeader title={'注册'}/>
                <View

                    style={{
                        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
                        paddingRight: CustomStyle.getActualSizeInHorizontal(20),
                        marginTop: CustomStyle.getActualSizeInVertical(180),
                    }}
                >
                    <View style={[styles.inputContainer, {}]}>
                        <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入手机号'}
                                   keyboardType='numeric'
                                   maxLength={11}
                                   underlineColorAndroid={'#00000000'}
                                   onChangeText={(value) => {
                                       this.setState({phone: value});
                                   }}
                        />
                    </View>


                    <View style={[styles.inputContainer, {marginTop: CustomStyle.getActualSizeInVertical(40),}]}>
                        <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入密码'}
                                   underlineColorAndroid={'#00000000'}
                                   onChangeText={(value) => {
                                       this.setState({password: value});
                                   }}
                        />
                    </View>

                    <View style={[styles.inputContainer, {marginTop: CustomStyle.getActualSizeInVertical(80),}]}>
                        <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'再次输入密码'}
                                   underlineColorAndroid={'#00000000'}
                                   onChangeText={(value) => {
                                       this.setState({passwordConfirm: value});
                                   }}
                        />
                    </View>


                    <View style={{flexDirection: 'row', flex: 1, marginTop: CustomStyle.getActualSizeInVertical(80),}}>
                        <View style={[styles.inputContainer, {
                            flex: 1,
                        }]}>
                            <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入验证码'}
                                       underlineColorAndroid={'#00000000'}
                                       onChangeText={(value) => {
                                           this.setState({verifyCode: value});
                                       }}
                            />
                        </View>
                        <TouchableOpacity
                            disabled={this.state.requestingVerifyCode}
                            style={[, {
                                width: CustomStyle.getActualSizeInHorizontal(230),
                                height: CustomStyle.getActualSizeInVertical(88),
                                backgroundColor: this.state.requestingVerifyCode ? '#ebebeb' : '#ffc000',
                                justifyContent: 'center',
                                alignItems: 'center',
                                marginLeft: CustomStyle.getActualSizeInHorizontal(20),
                                borderRadius: CustomStyle.getActualSizeInHorizontal(4),
                            }
                            ]}
                            onPress={() => {
                                this._requestVerifyCode();
                            }}
                        >
                            <Text style={[CustomStyle.baseText, {
                                fontSize: CustomStyle.getActualFontSize(),
                                color: 'white',
                            }]}>{this.state.verifyText}</Text>
                        </TouchableOpacity>
                    </View>

                    <TouchableHighlight
                        style={[styles.btContainer, {
                            backgroundColor: '#ff7200',
                            marginTop: CustomStyle.getActualSizeInVertical(80),
                        }]}
                        underlayColor='#ef6500'
                        onPress={() => {
                            this._register();
                        }}
                    >
                        <View >
                            <Text style={[CustomStyle.baseText, styles.btText,]}>注册</Text>
                        </View>
                    </TouchableHighlight>

                </View>
            </ScrollView>
        );
    }

    _requestVerifyCode() {
        if (!this.state.phone || this.state.phone.length < 11) {
            Alert.alert('请输入手机号');
            return;
        }

        if (this.state.requestingVerifyCode) {
            return;
        }

        this.state.requestingVerifyCode = true;
        this.interval && clearInterval(this.interval);
        this.cd = 60;
        this.interval = setInterval(
            () => {
                this.cd--;
                console.log('interval ' + this.cd);
                this.setState({
                    verifyText: this.cd === 0 ? '获取验证码' : this.cd + '秒',
                    requestingVerifyCode: this.cd !== 0
                });
                if (this.cd === 0) {
                    this.interval && clearInterval(this.interval);
                    this.interval = null;
                }
            }, 1000
        );

        const params = {
            phone: this.state.phone
        };
        Util.postServer('user/code', params, (result) => this._onGetVerifyCodeSuccess(result), (msg) => this._onGetVerifyCodeFailed(msg));
    }

    _onGetVerifyCodeSuccess(result) {
        if (result.status !== '0') {
            Toast.show(result.msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        }
        else {
            Toast.show("短信验证码已发送", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        }
    }

    _onGetVerifyCodeFailed(msg) {
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }

    _register() {
        if (this.state.phone && this.state.password && this.state.passwordConfirm && this.state.verifyCode) {
            if (this.state.passWord !== this.state.passWord2) {
                Alert.alert("错误", "两次输入的密码不一致");
                return;
            }
            const params = {
                phone: this.state.phone,
                code: this.state.verifyCode,
                password: this.state.password,
                userid: null
            };
            Util.postServer("user/reg", params, (result) => this._onRegisterSuccess(result), (msg) => this._onRegisterFailed(msg));
        } else {
            Alert.alert("错误", "请输入完整信息");
        }
    }

    // 注册成功回调
    _onRegisterSuccess(result) {
        if (result.status === '0') {
            const param = {
                id: result.data.user.userid,
                token: result.data.user.token,
                phone: result.data.user.phone,
                info: result.data.user,
            };

            Util.storage.save({
                key: 'users',
                id: '1000',
                rawData: param,
                expires: null
            });

            this.props.updateUser(param);

            Toast.show("注册成功", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
            Actions.pop({key: 'Mine'});
        }
        else {
            Alert.alert("注册失败", result.msg);
        }
    }

    // 注册失败回调
    _onRegisterFailed(msg) {
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }


}
const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {
        updateUser: param => dispatch(MineAction.userData(param)),
    };
};
export default connect(mapStateToProps, mapDispatchToProps)(Register);